import 'package:craze/common/index.dart';
import 'package:craze/common/widgets/bullet_point_text.dart';
import 'package:easy_image_viewer/easy_image_viewer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';

class KnowledgeDetailThreeView extends StatelessWidget {
  const KnowledgeDetailThreeView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: KnowledgeDetailBackground(
        child: Column(
          children: [
            const KnowledgeHeader(title: 'Knowledge'),
            Expanded(
              child: CustomScrollView(
                slivers: [
                  SliverPadding(
                    padding: EdgeInsets.symmetric(horizontal: 20.w),
                    sliver: SliverList(
                      delegate: SliverChildListDelegate([
                        SizedBox(height: 10.h),
                        const SectionTitle(
                          title: 'The fun and meaning of diving？',
                        ),
                        const SizedBox(height: 28),

                        const ContentBlock(
                          index: '1',
                          title: 'Explore the unknown world：',
                          bulletPoints: [
                            'Diving is the best way to the underwater world. After entering the ocean, you seem to become an adventurer, exploring an unknown secret world.',
                            'You may feel the satisfaction of "discovering a new world" and appreciate the most fantastic beauty of nature.',
                          ],
                        ),

                        const ContentBlock(
                          index: '2',
                          title: 'Close encounters with marine life:',

                          bulletPoints: [
                            'Diving provides you with a unique opportunity to observe marine life up close. From colorful tropical fish and leisurely swimming turtles to graceful manta rays and even whale sharks, you and these creatures swim in the same world, only an arm\'s length away.',
                          ],
                        ),

                        const ContentBlock(
                          index: '3',
                          title: 'The fun of challenging yourself:',

                          bulletPoints: [
                            'For novices, the process from learning diving skills to the first dive is full of excitement and challenges; for diving enthusiasts, diving at different depths, locations and environments is a new journey.',
                          ],
                        ),

                        ImageViewerWidget(imagePath: MyImages.knowledge5),

                        const SectionTitle(title: 'Diving for personal growth'),
                        const SizedBox(height: 28),

                        const ContentBlock(
                          index: '1',
                          title: 'Overcoming Fear:',
                          bulletPoints: [
                            'When first learning to dive, many people are afraid of the unknown of the deep sea, but when you overcome psychological barriers and go deep into the ocean, you will find a sense of confidence and accomplishment in facing the unknown.',
                          ],
                        ),
                        const ContentBlock(
                          index: '2',
                          title: 'Improve team awareness:',
                          bulletPoints: [
                            'Diving emphasizes the "buddy system". You must cooperate with your buddy and support each other. This team spirit not only provides safety underwater, but also cultivates better collaboration skills.',
                            'In the underwater world, time slows down. You focus on your breathing and the amazing scenery around you, and this focus teaches you how to appreciate every moment.',
                          ],
                        ),

                        SizedBox(height: 100.h),
                      ]),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 页面背景组件
class KnowledgeDetailBackground extends StatelessWidget {
  final Widget child;

  const KnowledgeDetailBackground({Key? key, required this.child})
    : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 1.sh,
      width: 1.sw,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(MyImages.commonBg),
          fit: BoxFit.cover,
        ),
      ),
      child: SafeArea(bottom: false, child: child),
    );
  }
}

/// 页面顶部标题组件
class KnowledgeHeader extends StatelessWidget {
  final String title;

  const KnowledgeHeader({Key? key, required this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => GoRouter.of(context).pop(),
            child: Icon(MyIcons.iconBack, color: Colors.white, size: 24.sp),
          ),
          Expanded(
            child: Text(
              title,
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white,
                fontSize: 22.sp,
                fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                fontWeight: FontWeight.w400,
                height: 1.36,
              ),
            ),
          ),
          // 为了保持左右对称，添加一个占位
          SizedBox(width: 24.sp),
        ],
      ),
    );
  }
}

/// 章节标题组件
class SectionTitle extends StatelessWidget {
  final String title;

  const SectionTitle({super.key, required this.title});

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.centerLeft,
      child: Text(
        title,
        style: TextStyle(
          color: Colors.white.withAlpha(230),
          fontSize: 22.sp,
          fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
          fontWeight: FontWeight.w400,
          height: 1.5,
        ),
      ),
    );
  }
}

/// 内容块组件（包含编号、标题和项目列表）
class ContentBlock extends StatelessWidget {
  final String index;
  final String title;
  final List<String> bulletPoints;

  const ContentBlock({
    super.key,
    required this.index,
    required this.title,
    required this.bulletPoints,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            NumberBadge(number: index),
            SizedBox(width: 10.w),
            Expanded(
              child: Text(
                title,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                  fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ],
        ),
        SizedBox(height: 20.h),
        ...bulletPoints.map(
          (text) => Padding(
            padding: EdgeInsets.only(left: 32.w, bottom: 18.h),
            child: BulletPointText(text: text),
          ),
        ),
        SizedBox(height: 10.h),
      ],
    );
  }
}

/// 编号徽章组件
class NumberBadge extends StatelessWidget {
  final String number;

  const NumberBadge({super.key, required this.number});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 40.w,
      height: 40.w,
      child: CustomPaint(
        painter: NumberBadgePainter(),
        child: Center(
          child: Transform.translate(
            offset: Offset(-1.w, 5.w),
            child: Transform.rotate(
              angle: -0.17,
              child: Text(
                number,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.sp,
                  fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                  fontWeight: FontWeight.w400,
                  height: 1,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

/// 编号徽章自定义绘制
class NumberBadgePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final backgroundPaint =
        Paint()
          ..color = const Color(0xFF003068)
          ..style = PaintingStyle.fill;

    final foregroundPaint =
        Paint()
          ..shader = const LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFF0076FF), Color(0xFF045EC6)],
          ).createShader(Rect.fromLTWH(0, 0, size.width, size.height));

    // 绘制背景方块（轻微旋转）
    canvas.save();
    canvas.translate(size.width * 0.5, size.height * 0.5);
    canvas.rotate(-0.17);
    canvas.drawRRect(
      RRect.fromRectAndRadius(
        Rect.fromCenter(
          center: Offset.zero,
          width: size.width * 0.6,
          height: size.height * 0.6,
        ),
        Radius.circular(size.width * 0.1),
      ),
      backgroundPaint,
    );
    canvas.restore();

    // 绘制前景方块（轻微旋转）
    canvas.save();
    canvas.translate(size.width * 0.5, size.height * 0.5);
    canvas.rotate(-0.17);
    canvas.drawRRect(
      RRect.fromRectAndRadius(
        Rect.fromCenter(
          center: Offset(size.width * -0.08, size.height * 0.08),
          width: size.width * 0.8,
          height: size.height * 0.8,
        ),
        Radius.circular(size.width * 0.15),
      ),
      foregroundPaint,
    );
    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

/// 图片查看组件
class ImageViewerWidget extends StatelessWidget {
  final String imagePath;

  const ImageViewerWidget({Key? key, required this.imagePath})
    : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 16.h),
      child: AspectRatio(
        aspectRatio: 374 / 190,
        child: GestureDetector(
          onTap: () => _showFullScreenImage(context, imagePath),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8.r),
            child: Image.asset(imagePath, fit: BoxFit.cover),
          ),
        ),
      ),
    );
  }

  void _showFullScreenImage(BuildContext context, String imagePath) {
    final imageProvider = AssetImage(imagePath);
    showImageViewer(
      context,
      imageProvider,
      swipeDismissible: true,
      doubleTapZoomable: true,
    );
  }
}
